<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/11
 * Time: 22:15
 */

namespace app\lib\exception;


use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    // 需要返回客户端当前请求的URL路径
    public function render(\Exception $err)
    {
        # 使其生效 需要在 config 里 异常处理Handle类出配置
        /*return json('~~~~',400);*/

        if ($err instanceof BaseException) {
            # 如果是自定义异常
            $this->code = $err->code;
            $this->msg = $err->msg;
            $this->errorCode = $err->errorCode;
        } else {
            # 用于客户端和服务端对不同调试信息的需求
            # 开发环境（应用调试模式） 不需要记录
            # Config::get('app_debug');
            if (config('app_debug')) {
                # return default error page
                return parent::render($err);
            } else {
                $this->code = 500;
                $this->msg = '服务器内部错误，不想告诉你';
                $this->errorCode = 999;
                $this->recordErrorLog($err);
            }
        }
        $request = Request::instance();
        $result = [
            'msg' => $this->msg,
            'error_code' => $this->errorCode,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }

    private function recordErrorLog(\Exception $err)
    {
        # config 里边关闭了 自动记录系统，在此处重新初始化
        Log::init([
            'type'=>'File',
            'path'=>LOG_PATH,
            'level'=>['error']
        ]);
        Log::record($err->getMessage(), 'error');
    }
}